<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
        <!--用户数据-->
        <pane size="84">
          <el-col>
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
              label-width="68px">
              <el-form-item label="手机号码" prop="phonenumber">
                <el-input v-model="queryParams.phoneNumber" placeholder="请输入手机号码" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="支付状态" clearable style="width: 240px">
                  <el-option v-for="dict in dict.type.order_state" :key="dict.value" :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>

              <el-form-item label-width="120px" label="创建时间" prop="daterange">
                <el-date-picker v-model="dateRange" type="daterange" value-format="yyyy-MM-dd" range-separator="至"
                  start-placeholder="开始日期" end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>

            <el-table v-loading="loading" :data="userList">
              <el-table-column type="selection" width="50" align="center" />
              <el-table-column label="用户ID" align="center" prop="userId" width="220" />
              <el-table-column label="用户名" align="center" prop="userName" width="120" />
              <el-table-column label="手机号码" align="center" prop="phoneNumber" width="120" />
              <el-table-column label="订单号" align="center" prop="orderNo" width="220" />
              <el-table-column label="订单时长(月)" align="center" prop="orderTime" min-width="120" />
              <el-table-column label="订单状态" align="center" prop="status" min-width="120" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.order_state" :value="scope.row.status" />
                </template>
              </el-table-column>
              <el-table-column label="订单金额" align="center" prop="orderAmount" min-width="120" />
              <el-table-column label="已退款金额" align="center" prop="refundAmount" min-width="120" />
              <el-table-column label="退款原因" align="center" prop="refundReason" min-width="120" />
              <el-table-column label="支付方式" align="center" prop="paymentMethod" min-width="120" />
              <el-table-column label="支付状态" align="center" prop="paymentStatus" min-width="120">
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.paymentStatus == 1" type="success">支付成功</el-tag>
                  <el-tag v-else type="danger">未支付</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="第三方支付平台的交易号" align="center" prop="tradeNo" width="240" />
              <el-table-column label="支付完成时间" align="center" prop="paymentTime" width="160">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.paymentTime) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="创建时间" align="center" prop="createTime" width="160"/>
              <el-table-column v-if="checkRole(['admin'])" label="操作" align="center" width="160" fixed="right"
                class-name="small-padding fixed-width">
                <template  slot-scope="scope" v-if="(scope.row.userId !== 1 && scope.row.status == 1) || (scope.row.status == 2 && (scope.row.orderAmount - scope.row.refundAmount)>0)">
                  <el-button size="mini" type="text" icon="el-icon-sold-out" @click="handleOrderRefund(scope.row)">退款</el-button>
                </template>
              </el-table-column>
            </el-table>

            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize" @pagination="getList" />
          </el-col>
        </pane>
      </splitpanes>
    </el-row>

    <!-- 退款确认框 -->
    <el-dialog title="退款" :visible.sync="refundShow" width="700px" append-to-body>
      <el-form ref="refundDate" :model="refundData" :rules="refundRules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="可退款金额" prop="remainingAmount">
              <span style="font-size: 20px; color: green;">{{ refundData.remainingAmount }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="退款金额（元）" prop="refundAmount">
              <el-input v-model="refundData.refundAmount" placeholder="请输入退款金额" type="number" maxlength="10" >
                <template slot="suffix">元 </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="退款原因" prop="refundReason">
              <el-input v-model="refundData.refundReason" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <span style="margin-right: 50px; font-size: 14px; font-weight: bold; color: red">已退款订单，不计入推广订单</span>
        <el-button type="primary" @click="refundSubmitForm()">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { checkPermi, checkRole } from "@/utils/permission"; // 权限判断函数
import {
  orderList,
  orderRefund, orderRefundQuery
} from "@/api/order/index";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";
import {addAppUser, getPromotionContentr, updateAppUser} from "@/api/system/user";

export default {
  name: "User",
  dicts: ["user_type", "sys_normal_disable", "sys_user_sex", "order_state"],
  components: { Splitpanes, Pane },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},

      // 退款数据
      refundData: {
        //userId
        refundUserId: undefined,
        refundOrderNo: undefined,
        //剩余金额
        remainingAmount: undefined,
        //退款金额
        refundAmount: undefined,
        //退款备注
        refundReason: undefined,
      },
      refundShow: false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: 'createTime',
        isAsc: 'descending',
        phoneNumber: undefined,
        status: undefined
      },

      // 退款校验
      refundRules: {
        refundAmount: [
          { required: true, message: "退款金额不能为空", trigger: "blur"},
          {
            pattern: /^[0-9]{1,10}(\.[0-9]{1,2})?$/,
            message: "请输入合法的金额，最多两位小数且不超过10位",
            trigger: "blur"
          },
          {
            validator: (rule, value, callback) => {
              // 校验 refundAmount 大于 0 且小于等于 remainingAmount
              if (value) {
                const refundAmount = parseFloat(value);
                const remainingAmount = parseFloat(this.refundData.remainingAmount);
                // 校验退款金额不能小于等于0
                if (refundAmount <= 0) {
                  callback(new Error("退款金额必须大于0"));
                }
                // 校验退款金额不能大于剩余金额
                else if (refundAmount > remainingAmount) {
                  callback(new Error(`退款金额不能大于剩余金额 ${remainingAmount}`));
                } else {
                  callback();  // 校验通过
                }
              } else {
                callback();  // 如果没有填写退款金额，直接通过
              }
            },
            trigger: "blur"
          }
        ],

        refundReason: [
          { required: true, message: "退款原因必填", trigger: "blur" },
        ],
      },
    };
  },
  watch: {
  },
  created() {
    this.getList();
    this.getConfigKey("sys.user.initPassword").then((response) => {
      this.initPassword = response.msg;
    });
  },
  methods: {
    checkPermi,
    checkRole,
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      orderList(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.refundShow = false
    },
    // 表单重置
    reset() {
      this.form = {
        phoneNumber: undefined,
        status: "0",
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    /** 退款按钮操作 */
    handleOrderRefund(row) {
      this.refundShow = true;
      this.refundData.remainingAmount = row.orderAmount - row.refundAmount;
      this.refundData.refundUserId = row.userId;
      this.refundData.refundOrderNo = row.orderNo;
    },

    /** 退款提交按钮 */
    refundSubmitForm: function () {
      this.$refs["refundDate"].validate((valid) => {
        if (valid) {
          orderRefund({
            userId: this.refundData.refundUserId,
            orderNo: this.refundData.refundOrderNo,
            refundAmount: this.refundData.refundAmount,
            refundReason: this.refundData.refundReason,
          }).then(res =>{
            if (res.code === 200){
              this.$modal.msgSuccess(res.data);
            }else{
              this.$modal.msgError(res.msg);
            }

            this.getList();
            this.refundShow = false;
            this.refundData.remainingAmount = undefined;
            this.refundData.refundAmount = undefined;
          })
        }
      });
    },
  },
};
</script>
